package com.weishui.dimensionalbarcode.logic;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;


public class DimensionalBarEncodeAndDecode {

	/**
	 * 二维码编码
	 * @param str  需要编码的字符串
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static File encode(String str) {
		try {
			SimpleDateFormat sdDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
			String path = "./encode" + sdDateFormat.format(new Date()) + ".png";
			int width = 180;  
		    int height = 160; 
			Hashtable hints = new Hashtable();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			BitMatrix byteMatrix;
			byteMatrix = new MultiFormatWriter().encode(str,BarcodeFormat.QR_CODE, width, height,hints);
			File file = new File(path);
			MatrixToImageWriter.writeToFile(byteMatrix, "png", file);
			return file;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
			
		}
	}

	/**
	 * 二维码解码
	 * @param file   需要解码的文件(如图片)
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Result decode(File file) {
		try {
			BufferedImage image;
			try {
				image = ImageIO.read(file);
				if (image == null) {
					System.out.println("Could not decode image");
				}
				LuminanceSource source = new BufferedImageLuminanceSource(image);
				BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
						source));
				Result result;
				Hashtable hints = new Hashtable();
				hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
				result = new MultiFormatReader().decode(bitmap, hints);
				return result;
			} catch (IOException ioe) {
				System.out.println(ioe.toString());
				return null;
			} catch (ReaderException re) {
				System.out.println(re.toString());
				return null;
			}
		} catch (Exception ex) {
			return null;
		}
	}
}
